package com.example.code06;

import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabaseLockedException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.net.PortUnreachableException;

public class MySQLLiteOpenHelper extends SQLiteOpenHelper {
    private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + NewsContract.NewsEntry.TABLE_NAME + "(" +
            NewsContract.NewsEntry._ID + " INTEGER PRIMARY KEY," + NewsContract.NewsEntry.COLUMN_NAME_TITLE + " VARCHAR(200), " +
            NewsContract.NewsEntry.COLUMN_NAME_AUTHOR + " VARCHAR(100), " + NewsContract.NewsEntry.COLUMN_NAME_CONTENT + " TEXT, " +
            NewsContract.NewsEntry.COLUMN_NAME_IMAGE + " VARCHAR(100) " + ")";
    private static final String SQL_DELETE_ENTRIES=
            "DROP TABLE IF EXISTS "+NewsContract.NewsEntry.TABLE_NAME;
    public static final int DATABASE_VERSION=2;
    public static final String DATABASE_NAME="news.db";
    private Context mcontext;
    public MySQLLiteOpenHelper(Context context){
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
        this.mcontext=context;
    }
    public void onCreate(SQLiteDatabase sqLiteDatabase){
        sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES);
        initDb(sqLiteDatabase);
    }
    private  void initDb(SQLiteDatabase sqLiteDatabase){
        Resources resources=mcontext.getResources();
        String[] titles=resources.getStringArray(R.array.titles);
        String[] authors=resources.getStringArray(R.array.authors);
        String[] contents=resources.getStringArray(R.array.contents);
        TypedArray images=resources.obtainTypedArray(R.array.images);

        int l=0;
        if(titles.length<authors.length){
            l=titles.length;
        }
        else{
            l=authors.length;
        }
        if(l>contents.length){
            l=contents.length;
        }
        if(l>images.length()){
            l=images.length();
        }
        for(int i=0;i<l;i++){
            ContentValues values=new ContentValues();
            values.put(NewsContract.NewsEntry.COLUMN_NAME_TITLE,titles[i]);
            values.put(NewsContract.NewsEntry.COLUMN_NAME_AUTHOR,authors[i]);
            values.put(NewsContract.NewsEntry.COLUMN_NAME_CONTENT,contents[i]);
            values.put(NewsContract.NewsEntry.COLUMN_NAME_IMAGE,images.getString(i));
            long r=sqLiteDatabase.insert(NewsContract.NewsEntry.TABLE_NAME,null,values);
        }
    }

    public void onUpgrade(SQLiteDatabase sqLiteDatabase,int oldversion,int newversion){
        sqLiteDatabase.execSQL(SQL_DELETE_ENTRIES);
        onCreate(sqLiteDatabase);
    }

}

